#include "statusbar.h"
#include "core/controller.h"
//#include "ukuiwindowhelper/ukuiwindowhelper.h"
#include "windowmanager/windowmanager.h"

#define THEME_SCHAME "org.ukui.style"

StatusBar::StatusBar(uint qId, QWidget *parent)
    : QWidget(parent),
      m_isLMousePress(false),
      m_relativePos(0,0),
      m_hp(HP_None),
      m_qId(qId)
{
    const QByteArray style_id(THEME_SCHAME);
    if(QGSettings::isSchemaInstalled(style_id)){
        m_styleSettings = new QGSettings(style_id);
    }
    m_isPaused = false;
    m_isClosedMicrophone = true;
    this->setAttribute(Qt::WA_TranslucentBackground);
    this->setWindowFlags( Qt::BypassWindowManagerHint| Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::Tool);
    this->setAttribute(Qt::WA_AlwaysShowToolTips);
    this->setProperty("useStyleWindowManager", false);

    if (!(m_info.waylandDectected() && !m_info.isHWWayland() && (m_info.windowManager() == DesktopInfo::UKUI)))
    {
//        WindowManager::setSkipTaskBar(this->windowHandle(), true);
//        WindowManager::setSkipSwitcher(this->windowHandle(), true);
    }
    else
    {
//        UkuiWindowHelper *windowHelper = new UkuiWindowHelper(this);
//        windowHelper->setSkipTaskBar(true);
//        windowHelper->setSkipSwitcher(true);
//        UkuiWindowHelper::States states;
//        states |= UkuiWindowHelper::State::KeepAbove;
//        windowHelper->setWindowState(states);
        KWindowSystem::setType(winId(), NET::OnScreenDisplay);
        kdk::WindowManager::setSkipTaskBar(this->windowHandle(), true);
        kdk::WindowManager::setSkipSwitcher(this->windowHandle(), true);
    }

    initLayout();
    initConnect();
    initGsetting();
    this->initFontSize();

    //录制窗口的框
    m_recordingWid = new RecordingWidget();
    m_btnWid->installEventFilter(this);
    //更新时间
    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&StatusBar::slotUpdateRecordingTime);

    //获取桌面宽度
    QRect rect = QGuiApplication::primaryScreen()->virtualGeometry();
    m_screenWidth = rect.width();
}


void StatusBar::setRecordingWid(QRect rect, uint winId)
{
    m_winId = winId;
    qDebug()<<"StatusBar::setRecordingWid 输入的rect："<<rect;
    m_recordingWid->setGeometry(rect.adjusted(-2,-2,2,2));  //大两圈

    // 计算状态栏的位置
    QRect recordingRect = m_recordingWid->geometry();   //计算状态栏位置所依据的主屏幕的录制区域大小
    if(rect == QGuiApplication::primaryScreen()->virtualGeometry()){
        recordingRect = QGuiApplication::primaryScreen()->geometry();
    }
    QPoint statusPos;
    statusPos.setX(recordingRect.x() + (recordingRect.width() - m_statusWid->width()) / 2);
    statusPos.setY(recordingRect.y() + recordingRect.height() + 12);

    QRect screenGeometry = QApplication::desktop()->screenGeometry();
    if((recordingRect.bottom() + 12 + m_statusWid->height()) > screenGeometry.bottom()){
        if((recordingRect.top() - 12 - m_statusWid->height()) > screenGeometry.top()){
            statusPos.setY(recordingRect.top() - 12 - m_statusWid->height());
        }else {
           statusPos.setY(recordingRect.top() + 12);
        }
    }

    this->move(statusPos);
    m_recordingWid->show();
}

void StatusBar::setRecordingStart()
{
    recordingStartTime = QTime::currentTime();
    startTime = QTime::currentTime();
    timer->stop();
    timer->start(1000);
    m_TimeRec->setText("00:00:00");
}

void StatusBar::setMicStatus(bool isOpenMic)
{
    //根据工具栏设置调整麦克风状态
    if(isOpenMic){
        m_isClosedMicrophone = false;
        m_btnMicrophoneRec->setIcon(QIcon(":/icon/status/volume_normal.svg"));
        m_btnMicrophoneRec->setToolTip(tr("turn off mic"));
        if(m_progressBar){
            m_progressBar->show();
        }
        Controller::getInstance()->openMicrophone();
    }else{
        m_isClosedMicrophone = true;
        m_btnMicrophoneRec->setIcon(QIcon(":/icon/status/volume_off.svg"));
        m_btnMicrophoneRec->setToolTip(tr("turn on mic"));
        if(m_progressBar){
            m_progressBar->hide();
        }
    }
}

void StatusBar::openMicIcon(bool isOpenMic)
{
    //仅改变麦克图标的开关状态
    if(isOpenMic){
        m_isClosedMicrophone = false;
        m_btnMicrophoneRec->setIcon(QIcon(":/icon/status/volume_normal.svg"));
        m_btnMicrophoneRec->setToolTip(tr("turn off mic"));
        if(m_progressBar){
            m_progressBar->show();
        }
    }else{
        m_isClosedMicrophone = true;
        m_btnMicrophoneRec->setIcon(QIcon(":/icon/status/volume_off.svg"));
        m_btnMicrophoneRec->setToolTip(tr("turn on mic"));
        if(m_progressBar){
            m_progressBar->hide();
        }
    }
}

void StatusBar::micIconGrayout(bool isOpenMic)
{
    if(isOpenMic){//不禁用麦克风
            m_btnMicrophoneRec->setEnabled(true);
            m_btnMicrophoneRec->setToolTip(tr("turn on mic"));

    }else{//禁用麦克风
        openMicIcon(false);
        m_btnMicrophoneRec->setEnabled(false);
        m_btnMicrophoneRec->setToolTip(tr("The microphone is currently unavailable"));
    }
}


void StatusBar::slotPauseOrResumeRec()
{
    //数据埋点 - 暂停录制
//    KTrackData *node = kdk_dia_data_init(KEVENTSOURCE_DESKTOP, KEVENT_CLICK);
//    kdk_dia_upload_default(node, "pause-or-resume-record", "StatusBar");
//    kdk_dia_data_free(node);

    if( !m_isPaused ){
        qDebug()<<"暂停录制";
        m_isPaused = true;
        m_btnPauseRec->setIcon(QIcon(":/icon/status/resume.svg"));
        m_btnPauseRec->setToolTip(tr("continue"));

        Controller::getInstance()->pauseRecord();

        pauseTime = QTime::currentTime();
        timer->stop();
        totle += startTime.msecsTo(pauseTime);

    }else {
        qDebug()<<"继续录制";
        m_isPaused = false;
        m_btnPauseRec->setIcon(QIcon(":/icon/status/pause.svg"));
        m_btnPauseRec->setToolTip(tr("pause"));

        Controller::getInstance()->contineRecord();

        startTime = QTime::currentTime();
        timer->start(1000);
    }
}

void StatusBar::slotStopRecAndSave()
{
    //数据埋点 - 停止录制
//    KTrackData *node = kdk_dia_data_init(KEVENTSOURCE_DESKTOP, KEVENT_CLICK);
//    kdk_dia_upload_default(node, "stop-and-save-record", "StatusBar");
//    kdk_dia_data_free(node);

    qDebug()<<"statusBar - 停止录制并保存";
    this->hide();
    m_recordingWid->hide();
    if (m_isPaused)
    {
        m_isPaused = false;
        m_btnPauseRec->setIcon(QIcon(":/icon/status/pause.svg"));
        m_btnPauseRec->setToolTip(tr("pause"));
        Controller::getInstance()->contineRecord();
    }

    emit sigCloseRec();
    Controller::getInstance()->stopRecord(m_qId);
    timer->stop();
    totle = 0;
    if(m_isClosedMicrophone){
       Controller::getInstance()->openMicrophone();
    }
}

void StatusBar::slotCloseMicrophone( )
{
    //数据埋点 - 关闭麦克风
//    KTrackData *node = kdk_dia_data_init(KEVENTSOURCE_DESKTOP, KEVENT_CLICK);
//    kdk_dia_upload_default(node, "close-or-open-microphone", "StatusBar");
//    kdk_dia_data_free(node);

    if( !m_isClosedMicrophone){
        qDebug()<<"关闭麦克风";
        openMicIcon(false);

        Controller::getInstance()->closeMicrophone();
    }else {
        qDebug()<<"开启麦克风";
        if(!m_btnMicrophoneRec->isEnabled()){
            return;
        }
        openMicIcon(true);

        Controller::getInstance()->openMicrophone();
    }
}

void StatusBar::setQId(uint qId)
{
    m_qId = qId;
}

void StatusBar::slotSavedSucceed(bool isSavedSucceed)
{

}

void StatusBar::slotUpdateRecordingTime()
{
    int elapsed = startTime.msecsTo(QTime::currentTime());
    QTime time = QTime(0,0).addMSecs(totle + elapsed);
    m_TimeRec->setText(time.toString("hh:mm:ss"));

    checkWindowPosChange();
}

void StatusBar::slotUpdateVolume(int newVolume)
{
    if(!m_isClosedMicrophone && m_progressBar ){
        if(newVolume < m_progressBar->maximum()){
            m_progressBar->setValue(newVolume);
            m_progressBar->update();
        }
    }
}

void StatusBar::initLayout()
{
    //X11窗口装饰
    MotifWmHints hints1;
    hints1.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
    hints1.functions = MWM_FUNC_ALL;
    hints1.decorations = MWM_DECOR_BORDER;
    XAtomHelper::getInstance()->setWindowMotifHint(this->winId(), hints1);

    QHBoxLayout *m_layout = new QHBoxLayout(this);
    m_statusWid = new QWidget (this);
    QHBoxLayout *m_statusWidLayout = new QHBoxLayout(m_statusWid);
    //按钮窗口
    m_btnWid = new QWidget(m_statusWid);
    QHBoxLayout *m_btnLayout = new QHBoxLayout(m_btnWid);
    m_btnPauseRec = new kdk::KBorderlessButton(m_btnWid);
    m_btnPauseRec->setFocusPolicy(Qt::NoFocus);
    m_btnPauseRec->setAttribute(Qt::WA_TranslucentBackground);
    m_btnStopRec = new kdk::KBorderlessButton(m_btnWid);
    m_btnStopRec->setFocusPolicy(Qt::NoFocus);
    m_btnStopRec->setAttribute(Qt::WA_TranslucentBackground);
    m_btnMicrophoneRec = new kdk::KBorderlessButton(m_btnWid);
    m_btnMicrophoneRec->setFocusPolicy(Qt::NoFocus);
    m_btnMicrophoneRec->setAttribute(Qt::WA_TranslucentBackground);


    //音量进度条
    setLevelMeter();

    m_line1 = new QLabel(m_statusWid);

    m_TimeRec = new QLabel(m_statusWid);
    m_TimeRec->setText("00:00:00");

    m_btnLayout->setSpacing(2);
    m_btnLayout->addWidget(m_btnPauseRec, 0, Qt::AlignCenter);
    m_btnLayout->addWidget(m_btnStopRec, 0, Qt::AlignCenter);
    m_btnLayout->addWidget(m_btnMicrophoneRec, 0, Qt::AlignCenter);
    m_btnLayout->setContentsMargins(0,0,0,0);
    m_statusWidLayout->setSpacing(12);
    m_statusWidLayout->addWidget(m_btnWid, 0, Qt::AlignCenter);
    m_statusWidLayout->addWidget(m_line1, 0, Qt::AlignCenter);
    m_statusWidLayout->addWidget(m_TimeRec, 0, Qt::AlignCenter);
    m_statusWidLayout->setContentsMargins(14,10,18,10);

    m_layout->addWidget(m_statusWid);

    setFixedSize(278,66);
    setBtnSize();
    setBtnIconSize();
    setBtnIcon();
    setTooltips();

    changeStyle();

    //绘制阴影
    QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect(this);
    effect->setOffset(0, 0); //设置向哪个方向产生阴影效果(dx,dy)，特别地，(0,0)代表向四周发散
    effect->setColor(TOOL_COLOR);       //设置阴影颜色，也可以setColor(QColor(220,220,220))
    effect->setBlurRadius(BLUR_RADIUS); //设定阴影的模糊半径，数值越大越模糊
    m_statusWid->setGraphicsEffect(effect);
}

void StatusBar::initConnect()
{
    connect(m_btnPauseRec, &kdk::KBorderlessButton::clicked, this,&StatusBar::slotPauseOrResumeRec);
    connect(m_btnStopRec, &kdk::KBorderlessButton::clicked, this,&StatusBar::slotStopRecAndSave);
    connect(m_btnMicrophoneRec, &kdk::KBorderlessButton::clicked, this,&StatusBar::slotCloseMicrophone);
}

void StatusBar::setBtnSize()
{
    m_btnPauseRec->setFixedSize(QSize(36,36));
    m_btnStopRec->setFixedSize(QSize(36,36));
    m_btnMicrophoneRec->setFixedSize(QSize(36,36));
    m_line1->setFixedSize(QSize(1,16.33));
    m_TimeRec->setFixedSize(QSize(36,36));

    m_statusWid->setFixedSize(268,56);
    m_btnWid->setFixedWidth(120);
    m_TimeRec->setFixedWidth(85);
}

void StatusBar::setBtnIconSize()
{
    m_btnPauseRec->setIconSize(QSize(24,24));
    m_btnStopRec->setIconSize(QSize(24,24));
    m_btnMicrophoneRec->setIconSize(QSize(24,24));
}

void StatusBar::setBtnIcon()
{
    m_btnPauseRec->setIcon(QIcon(":/icon/status/pause.svg"));
    m_btnStopRec->setIcon(QIcon(":/icon/status/stop.svg"));
    m_btnMicrophoneRec->setIcon(QIcon(":/icon/status/volume_normal.svg"));
}

void StatusBar::setTooltips()
{
    m_btnPauseRec->setToolTip(tr("pause"));//继续录屏
    m_btnStopRec->setToolTip(tr("stop and save"));
    m_btnMicrophoneRec->setToolTip(tr("turn off mic"));

    m_statusWid->setToolTip(tr("This bar can be dragged and held down, or hidden on the right side of the screen"));
    m_btnWid->setToolTip("");
    m_btnWid->setObjectName("myButtonWidget");
}

void StatusBar::changeStyle()
{
    QString nowThemeStyle = m_styleSettings->get("styleName").toString();
    if ("ukui-dark" == nowThemeStyle || "ukui-black" == nowThemeStyle) {
        m_line1->setStyleSheet("QLabel{border: 1px solid #727272;background-color: #727272;}");
        m_statusWid->setStyleSheet("QWidget{background-color:rgba(0,0,0,0.75);"
                                   "border:none;"
                                   "border-radius:12px;"
                                   "}");
        m_TimeRec->setStyleSheet("QLabel{border:none; background:transparent; border-radius:6px;color: white}");
    }else{
        m_line1->setStyleSheet("QLabel{border: 1px solid #393939;background-color: #393939;}");
        m_statusWid->setStyleSheet("QWidget{background-color:rgba(255, 255, 255, 0.75);"
                                   "border:none;"
                                   "border-radius:12px;"
                                   "}");
        m_TimeRec->setStyleSheet("QLabel{border:none; background:transparent; border-radius:6px;color: black}");
    }
    m_btnWid->setStyleSheet("QWidget{border:none; background:transparent; border-radius:6px;}");
}

void StatusBar::initGsetting()
{
    connect(m_styleSettings,&QGSettings::changed,this,[=](const QString &key) {
        if ("themeColor" == key || "styleName" == key) {
            changeStyle();
        }
    });
    changeStyle();
}

void StatusBar::initFontSize()
{
    //只有非标准字号的控件才需要绑定
    connect(this, &StatusBar::setFontSizeSignal, this, &StatusBar::lable2SetFontSizeSlot);
    connect(m_styleSettings,&QGSettings::changed,this,[=](const QString &key) {
        if (key == "systemFontSize" || key == "systemFont") {
            QString fontStyle = m_styleSettings->get("systemFont").toString();
            int fontSizeKey = m_styleSettings->get("systemFontSize").toString().toInt();
            if (fontSizeKey > 0) {
                if (fontSizeKey > 15) {
                    fontSizeKey = 15;
                }
                Q_EMIT setFontSizeSignal(fontSizeKey);
            }
        }
    });
    //启动时设置字号
    int fontSizeKey = 11; //系统默认字号
    int fontSizeKeyTmp = m_styleSettings->get("systemFontSize").toString().toInt();
    if (fontSizeKeyTmp > 0) {
        fontSizeKey = fontSizeKeyTmp;
    }
    if (fontSizeKey > 15) {
        fontSizeKey = 15;
    }
    Q_EMIT setFontSizeSignal(fontSizeKey);
}

void StatusBar::lable2SetFontSizeSlot(int size)
{
    //默认大小12px,换算成pt为9
    double lable2BaseFontSize = DEFAULT_FONT_SIZE;
    double nowFontSize = lable2BaseFontSize * double(size) / DEFAULT_FONT_SIZE; // 11为系统默认大小
    QFont font;
    font.setPointSizeF(nowFontSize);
    m_TimeRec->setFont(font);
}

void StatusBar::setLevelMeter()
{
    m_progressBar = new CustomProgressBar(m_btnMicrophoneRec);
    m_progressBar->setTextVisible(false);
    m_progressBar->setOrientation(Qt::Vertical);
    m_progressBar->setFixedSize(7,10);
    m_progressBar->move(8 + 6 ,4 + 6);
    m_progressBar->setRange(0, 100);

    m_progressBar->setValue(0);
}

void StatusBar::keyPressEvent(QKeyEvent *e)
{
    if (m_info.waylandDectected() && (m_info.windowManager() == DesktopInfo::UKUI))
    {
        if (Global::isRecordKey)
        {
            QString sKeyName = "";
            if (e->key() == Qt::Key_Shift)
            {
                sKeyName = "Shift";
            }
            else if (e->key() == Qt::Key_Control)
            {
                sKeyName = "Ctrl";
            }
            else if (e->key() == Qt::Key_CapsLock)
            {
                sKeyName = "Caps";
            }
            else
            {
                QKeySequence keySequence(e->key());
                sKeyName = keySequence.toString(QKeySequence::PortableText);;
            }

            qDebug() << "Key Name:" << sKeyName;
//            m_showKeyController->showScreenkeyWindow(sKeyName);
        }
    }

    QWidget::keyPressEvent(e);
}

//隐藏窗口的动画
void StatusBar::hideWindow()
{
    QPropertyAnimation * animation = new QPropertyAnimation(this, "geometry");
    animation->setStartValue(QRect(x(),y(),width(),height()));
    if(m_hp == HP_Top)
        animation->setEndValue(QRect(x(),20-height(),width(),height()));
    else if(m_hp == HP_Left)
        animation->setEndValue(QRect(20-width(),y(),width(),height()));
    else if(m_hp == HP_Right)
        animation->setEndValue(QRect(m_screenWidth-20,y(),width(),height()));
    animation->setDuration(250);
    animation->start();
}

//显示窗口的动画
void StatusBar::showWindow()
{
    QPropertyAnimation * animation = new QPropertyAnimation(this, "geometry");
    animation->setStartValue(QRect(x(),y(),width(),height()));
    if(m_hp == HP_Top)
        animation->setEndValue(QRect(x(),0,width(),height()));
    else if(m_hp == HP_Left)
        animation->setEndValue(QRect(0,y(),width(),height()));
    else if(m_hp == HP_Right)
        animation->setEndValue(QRect(m_screenWidth-width(),y(),width(),height()));
    animation->setDuration(250);
    animation->start();
}

void StatusBar::checkWindowPosChange()
{
    if (m_winId == 0)
    {
        return;
    }

    auto screenNumber = QApplication::desktop()->screenNumber();
    QScreen *screen = QApplication::screens()[screenNumber];
    QList<WId> windows = KWindowSystem::stackingOrder();    // 当前窗口活跃状态存储窗口ID
    for (WId id: windows)
    {
        if (id == m_winId)
        {
            KWindowInfo info(id, NET::WMState);                 // 判断窗口是否在处在激活状态
            if (info.hasState(NET::Hidden))
            {
                return;
            }

            KWindowInfo desktop_info(id, NET::WMDesktop);       // 判断窗口是否在当前截图桌面
            if (desktop_info.isOnCurrentDesktop()) { // 判断窗口是否显示
                KWindowInfo info2(id, NET::WMFrameExtents);
                QRect rect(info2.frameGeometry().x() / screen->devicePixelRatio(),
                           info2.frameGeometry().y() / screen->devicePixelRatio(),
                           info2.frameGeometry().width() / screen->devicePixelRatio(),
                           info2.frameGeometry().height() / screen->devicePixelRatio());
                if (m_recordingWid->geometry() != rect)
                {
                    //m_recordingWid->setGeometry(rect);
                }
            }

            return;
        }
    }
}

void StatusBar::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        m_isLMousePress = true;
        m_relativePos = event->globalPos() - pos();//记录相对位置
    }

    QWidget::mousePressEvent(event);
}

void StatusBar::mouseReleaseEvent(QMouseEvent *event)
{
    m_isLMousePress = false;

    QWidget::mouseReleaseEvent(event);
}

bool StatusBar::isWindowInScreen(QPoint pos)
{
    QRect rect = QGuiApplication::primaryScreen()->virtualGeometry();
    m_screenWidth = rect.width();
    if(pos.x()<5){
        m_hp = HP_Left;
        return false;
    }
    else if(pos.x()+ width()>m_screenWidth-5){
        m_hp = HP_Right;
        return false;
    }
    else if(pos.y()<5){
        m_hp = HP_Top;
        return false;
    }
    else{
        m_hp = HP_None;
        return true;
    }
}

void StatusBar::mouseMoveEvent(QMouseEvent *event)
{
    if(m_isLMousePress && isWindowInScreen(pos()))
    {
        move(event->globalPos()-m_relativePos);//实现无边框移动
    }
    else if(m_isLMousePress && !isWindowInScreen(pos()))
    {
        //特殊位置，移动规则不同
        int x = event->globalPos().x();
        int y = event->globalPos().y();
        if(m_hp == HP_Top)
        {
            move(x-m_relativePos.x(),y-m_relativePos.y());
        }
        else if(m_hp == HP_Left)
        {
            move(x-m_relativePos.x(),y-m_relativePos.y());
        }
        else if(m_hp == HP_Right)
        {
            move(x-m_relativePos.x(),y-m_relativePos.y());
        }
    }

    QWidget::mouseMoveEvent(event);
}

void StatusBar::enterEvent(QEvent *event)
{
    QRect rect = QGuiApplication::primaryScreen()->virtualGeometry();
    m_screenWidth = rect.width();

//    if (m_info.waylandDectected() || m_info.isWaylandDisplay())
    {
        if (!m_isLMousePress && !isWindowInScreen(pos()) && (m_hp == HP_Right))
        {
            qDebug()<<"StatusBar::enterEvent";
            move(m_screenWidth-270, y());
        }
        setFixedWidth(278); //不同分辨率切換時，有可能是寬度爲20的情況
    }
//    else
//    {
//        if(m_hp != HP_None)
//        {
//            showWindow();
//        }
//    }

    QWidget::enterEvent(event);
}

void StatusBar::leaveEvent(QEvent *event)
{
    QRect rect = QGuiApplication::primaryScreen()->virtualGeometry();
    m_screenWidth = rect.width();
//    if (m_info.waylandDectected() || m_info.isWaylandDisplay())
    {
        if (!m_isLMousePress && !isWindowInScreen(pos()) && (m_hp == HP_Right))
        {
            qDebug()<<"StatusBar::leaveEvent";
            setFixedWidth(20);
            move(m_screenWidth-20, y());
        }
    }
//    else
//    {
//        if(m_hp != HP_None)
//        {
//            hideWindow();
//        }
//    }

    QWidget::leaveEvent(event);
}

void StatusBar::moveEvent(QMoveEvent *event)
{
    QWidget::moveEvent(event);
}
